<?php

namespace app\common\controller;

use app\model\archives_model\UserArchiveModel;
use app\model\ConfigModel;
use app\model\ConsultBlacklistModel;
use app\model\ConsultOfflineModel;
use app\model\ConsultOfflineResultModel;
use app\model\ConsultOnlineMessageModel;
use app\model\ConsultOnlineModel;
use app\model\ConsultOnlineResultModel;
use app\model\CrisisLogModel;
use app\model\CrisisUserModel;
use app\model\DepartmentLevelModel;
use app\model\DepartmentModel;
use app\model\FollowUserModel;
use app\model\group_activity\GroupActivityTaskModel;
use app\model\group_activity\GroupActivityTaskUserModel;
use app\model\InterfereUserModel;
use app\model\InterpretationRecordModel;
use app\model\LoginLogModel;
use app\model\LogModel;
use app\model\MessageModel;
use app\model\platform\PlatformTaskModel;
use app\model\platform\PlatformTaskUnitModel;
use app\model\ProxyEvaluationResultModel;
use app\model\questionnaire\QuestionnaireTaskModel;
use app\model\SelfEvaluationResultModel;
use app\model\TaskModel;
use app\model\TaskUserModel;
use app\model\TaskUserResultContinuityModel;
use app\model\TaskUserResultModel;
use app\model\training\TrainingTaskModel;
use app\model\UnitModel;
use app\model\UserModel;
use app\model\WarningReportRecordModel;
use app\model\WorkersTaskModel;
use think\App;
use think\facade\Log;

/**
 * 该文件代码不能写事务
 */
class Task
{
    /**
     * 应用实例
     * @var App
     */
    protected App $app;

    /**
     * 构造方法
     * @access public
     * @param App $app 应用对象
     */
    public function __construct(App $app)
    {
        $this->app = $app;
    }

    /**
     * 执行定时任务（优化版）
     */
    public function runTask(array $taskConfig): void
    {
        foreach ($taskConfig as $task) {
            try {
                $this->executeTask($task['name']);
            } catch (\Throwable $e) {
                $this->logError($task['name'], $e);
            }
        }
    }

    /**
     * 任务执行路由
     */
    private function executeTask(string $taskName): void
    {
        match ($taskName) {
            'PlatformTask' => $this->platformTask(),
            'UpdateTaskStatus' => $this->updateTaskStatus(),
            'UpdateWorkersTaskStatus' => $this->UpdateWorkersTaskStatus(),
            'remind' => $this->Remind(),
            'crisisRemind' => $this->CrisisRemind(),
            'graduate' => $this->Graduate(),
            'groupActivityTask' => $this->groupActivityTask(),
            'trainingTask' => $this->trainingTask(),
            'consultOffline' => $this->consultOffline(),
            'questionnaireTask' => $this->questionnaireTask(),
            default => throw new \InvalidArgumentException("未知任务: {$taskName}")
        };
    }

    /**
     * 记录任务错误日志
     */
    private function logError(string $taskName, \Throwable $e): void
    {
        // 实现日志记录逻辑
        Log::channel('task')->error("[TaskError] {$taskName}: {$e->getMessage()}");
    }


    /**
     * 更新测评任务状态
     */
    public function UpdateTaskStatus(): void
    {
        $TaskModel = new TaskModel();
        $MessageModel = new MessageModel();
        $data = $TaskModel->where([
            ['status', 'in', [1, 2]],
            ['is_time', '=', 1]
        ])->select()->toArray();
        if (!empty($data)){
            $status2 = [];
            $status3 = [];
            $time = time();
            $MessageData = [];
            foreach ($data as $value) {
                if ($time > $value['end_time']) {
                    $status3[] = $value['id'];
                    $MessageData[] = [
                        'uid' => $value['uid'],
                        'type' => 7,
                        'title' => '任务期限通知',
                        'content' => '您发布的' . $value['name'] . '测评任务,已于' . date('Y-m-d', $value['end_time']) . '日期' . date('H:i:s', $value['end_time']) . '时间结束。',
                        'time' => time()
                    ];
                    continue;
                }
                if ($time > $value['start_time'] && $value['status'] == 1) {
                    $status2[] = $value['id'];
                }
            }
            if (!empty($status2)) {
                $TaskModel->where('id', 'in', $status2)->update(['status' => 2]);
            }
            if (!empty($status3)) {
                $TaskModel->where('id', 'in', $status3)->update(['status' => 3]);
            }
            if (!empty($MessageData)) {
                $MessageModel->insertAll($MessageData, 200);
            }
        }
    }

    /**
     * 更新测评任务状态-教职工
     */
    public function UpdateWorkersTaskStatus(): void
    {
        $WorkersTaskModel = new WorkersTaskModel();
        $data = $WorkersTaskModel->where([
            ['status', 'in', [1, 2]],
            ['is_time', '=', 1]
        ])->select()->toArray();
        if (!empty($data)){
            $status2 = [];
            $status3 = [];
            $time = time();
            foreach ($data as $value) {
                if ($time > $value['end_time']) {
                    $status3[] = $value['id'];
                    continue;
                }
                if ($time > $value['start_time']) {
                    $status2[] = $value['id'];
                }
            }
            if (!empty($status2)) {
                $WorkersTaskModel->where('id', 'in', $status2)->update(['status' => 2]);
            }
            if (!empty($status3)) {
                $WorkersTaskModel->where('id', 'in', $status3)->update(['status' => 3]);
            }
        }
    }

    /**
     * 提醒消息
     */
    public function remind(): void
    {
        $UserModel = new UserModel();
        $UserArchiveModel = new UserArchiveModel();
        $data = $UserModel->where('role_mode', '=', 3)->select()->toArray();
        $MessageData = [];
        foreach ($data as $value) {
            $info = $UserArchiveModel->where([
                ['type_id', '=', 1],
                ['user_id', '=', $value['id']]
            ])->order('id desc')->find();
            if ($info) {
                $MessageData[] = [
                    'uid' => $value['id'],
                    'type' => 2,
                    'title' => '个人自评信息',
                    'content' => '您已经很久没有更新个人自评信息了，上次更新于' . date('Y-m-d', $info['time']) . '日期' . date('H:i:s', $info['time']) . '时间，请尽快更新吧。',
                    'time' => time()
                ];
            } else {
                $MessageData[] = [
                    'uid' => $value['id'],
                    'type' => 2,
                    'title' => '个人自评信息',
                    'content' => '您还没有更新个人自评信息，请尽快更新吧。',
                    'time' => time()
                ];
            }
        }
        if (!empty($MessageData)){
            $MessageModel = new MessageModel();
            $MessageModel->insertAll($MessageData, 200);
        }
    }

    /**
     * 危机干预-提醒消息
     */
    public function crisisRemind(): void
    {
        $CrisisLogModel = new CrisisLogModel();
        $UserModel = new UserModel();
        $data = $CrisisLogModel->field('id,uid,remind_uid')->where('remind_time', 'between', [10, time()])->select()->toArray();
        if (!empty($data)) {
            $MessageData = [];
            $uid = array_column($data, 'uid');
            $user = $UserModel->where('id', 'in', $uid)->with(['departmentName'])->select()->toArray();
            $userData = [];
            foreach ($user as $v){
                $userData[$v['id']] = $v;
            }
            foreach ($data as $value) {
                $MessageData[] = [
                    'uid' => $value['remind_uid'],
                    'type' => 16,
                    'title' => 'remind_uid',
                    'content' => '您设置了对' . $userData[$value['uid']]['department_name']??' ' . '部门' . $userData[$value['uid']]['name']??' ' . '用户的危机干预事件跟进提醒。请及时进行处理。',
                    'time' => time()
                ];
            }
            $ids = array_column($data, 'id');
            $CrisisLogModel->where('id', 'in', $ids)->update([
                'remind_time' => 0
            ]);
            if (!empty($MessageData)){
                $MessageModel = new MessageModel();
                $MessageModel->insertAll($MessageData, 200);
            }
        }
    }

    /**
     * 学院制【到期自动升级】
     */
    public function graduate(): void
    {
        $UnitModel = new UnitModel();
        $userMode = new UserModel();
        $DepartmentLevelModel = new DepartmentLevelModel();
        $departmentModel = new DepartmentModel();
        $ConfigModel = new ConfigModel();

        $unit_list = $UnitModel->column('id');
        foreach ($unit_list as $unit_id) {
            $config = $ConfigModel->where([
                'unit_id' => $unit_id,
                'key' => 'department_management'
            ])->value('value')??'';
            $config = json_decode($config,true);
            if ($config['type'] != 2) continue;
            //获取设置的升级日期
            $expiration_date = strtotime(date('Y-' . $config['upgrade_time_month'] . '-' . $config['upgrade_time_day']));
            //判断是否要自动升级【大于等于设置的时间戳】
            if (time() < $expiration_date) continue;
            if (!empty($config['upgrade_date']) && date('Y') == $config['upgrade_date']) continue;
            $config['upgrade_date'] = date('Y');
            $ConfigModel->where([
                'unit_id' => $unit_id,
                'key' => 'department_management'
            ])->update([
                'value' => json_encode($config,true)
            ]);
            /**
             * 开始自动升级处理数据
             * 1.判断是不是升级到最后一级
             *      1.1:没到最后，
             *          1.1.1：【部门表】升一级（stage+1），
             *          1.1.2：【部门表】更改部门的名称为升级之后的名称
             *      1.2:到最后【判断设置：毕业后用户处理（end_status==1：直接删除用户所有资料）、==2：保留资料】，
             *          1.2.1：判断end_status的值，
             *              1.2.2.1：（等于1：删除资料）
             *                  一、【所有与用户相关的表的资料】删除用户：（删除语句）
             *                  -----其他的表（与用户相关的表）一样处理------
             *              1.2.2.2：（等于2：保留资料）
             *                  一、【用户表】修改用户的学籍状态：改为毕业（student_status==2）
             *                  二、【用户表】修改用户的账号状态：改为禁止登录（status==2）
             *                  三、【用户表】修改用户的账号状态：改为已删除（is_del==1）
             *                  -----其他的表（与用户相关的表）一样处理------
             *          1.2.2：【部门表】删除这个部门（id_del==1），
             *          1.2.3：【部门管理员表】删除这个部门管理员（id_del==1），
             *
             * */
            //查询学制阶段的数据【如果单位内有多个规则，循环处理】
            $levelList = $DepartmentLevelModel->where([
                ['unit_id', '=', $unit_id],
                ['status', '=', '1']
            ])->field('id,level_rules')->select()->toArray();
            $levelData = [];
            foreach ($levelList as $v) {
                $levelData[$v['id']] = json_decode($v['level_rules'],true);
            }
            $departmentId = $departmentModel->where([
                ['unit_id', '=', $unit_id],
                ['level', '=', 1]
            ])->column('id');
            foreach ($departmentId as $v) {
                //查询单位内所有得部门
                $departmentList = $departmentModel->where([
                    ['unit_id', '=', $unit_id],
                    ['level', '=', 2],
                    ['pid','=',$v]
                ])->field('id,level,name,mode,stage')->select()->toArray();
                $departmentData = [];
                foreach ($departmentList as $department) {
                    $departmentData[$department['stage']] = $department['id'];
                }
                foreach ($departmentList as $vv) {
                    //获取当前部门层级得学制阶段信息
                    $level_rule = $levelData[$vv['mode']];
                    //判断是不是升级到最后一级
                    $vv['stage']++;
                    if (!empty($level_rule[$vv['stage']])) {//不是最后一级
                        $departmentSaveData[$departmentData[$vv['stage']]] = $departmentModel->where('pid','=',$vv['id'])->column('id');
                    } else {//是最后一级
                        $departmentDelId[] = $vv['id'];
                    }
                }
            }
            if (!empty($departmentSaveData)){
                foreach ($departmentSaveData as $k => $v) {
                    if (!empty($v)){
                        $departmentModel->where('id', 'in', $v)->update([
                            'pid' => $k,
                        ]);
                    }
                }
            }
            if (!empty($departmentDelId)){
                //获取要操作得所有用户id
                $ids = $userMode->where('department_id', 'in', $departmentDelId)->column('id');
                if ($ids) {
                    $UnitModel->where('id','=',$unit_id)->dec('add_user_num',count($ids))->save();
                    if ($config['end_status'] == 2) {//保留资料
                        //修改普通用户信息
                        $userUpdate = [
                            'student_status' => 2,
                            'status' => 2,
                            'is_del' => 1,
                            'del_time' => time(),
                        ];
                        $userMode->where('department_id', 'in', $departmentDelId)->update($userUpdate);
                        $tempUpdate = [
                            'is_del' => 1,
                            'del_time' => time(),
                        ];
                        //开始伪删除与用户相关得数据
                        ConsultBlacklistModel::query()->where('uid', 'in', $ids)->update($tempUpdate);//心理咨询-黑名单表
                        ConsultOfflineModel::query()->where('uid', 'in', $ids)->update($tempUpdate);//线下咨询表
                        ConsultOfflineResultModel::query()->where('uid', 'in', $ids)->update($tempUpdate);//线下咨询量表测评结果表
                        ConsultOnlineModel::query()->where('uid', 'in', $ids)->update($tempUpdate);//线上咨询表
                        ConsultOnlineMessageModel::query()->where([['uid', 'in', $ids], ['who', '=', 1]])->update($tempUpdate);//线上咨询内容表
                        ConsultOnlineResultModel::query()->where('uid', 'in', $ids)->update($tempUpdate);//线上咨询量表测评结果表
                        CrisisLogModel::query()->where('uid', 'in', $ids)->update($tempUpdate);//危机干预-消息记录盒表
                        CrisisUserModel::query()->where('uid', 'in', $ids)->update($tempUpdate);//危机用户（危机上报）表
                        FollowUserModel::query()->where('uid', 'in', $ids)->update($tempUpdate);//关注用户（关注人群）表
                        InterfereUserModel::query()->where('uid', 'in', $ids)->update($tempUpdate);//干预人群表
                        InterpretationRecordModel::query()->where('uid', 'in', $ids)->update($tempUpdate);//申请解读记录表
                        LogModel::query()->where('uid', 'in', $ids)->update($tempUpdate);//系统日志表
                        LoginLogModel::query()->where('uid', 'in', $ids)->update($tempUpdate);//用户登录日志表
                        MessageModel::query()->where('uid', 'in', $ids)->update($tempUpdate);//用户接收的消息表
                        ProxyEvaluationResultModel::query()->where('uid', 'in', $ids)->update($tempUpdate);//代理测评结果（他人代测）表
                        SelfEvaluationResultModel::query()->where('uid', 'in', $ids)->update($tempUpdate);//自我测评结果表
                        TaskUserModel::query()->where('uid', 'in', $ids)->update($tempUpdate);//测评任务用户表
                        TaskUserResultModel::query()->where('uid', 'in', $ids)->update($tempUpdate);//任务用户答题结果表
                        TaskUserResultContinuityModel::query()->where('uid', 'in', $ids)->update($tempUpdate);//任务用户答题结果（因子预警连续测评）表
                        UserArchiveModel::query()->where('uid', 'in', $ids)->update($tempUpdate);//用户档案表
                        WarningReportRecordModel::query()->where('uid', 'in', $ids)->update($tempUpdate);//预警报告记录
//                            $userMode->where('id', 'in', $ids)->update($tempUpdate);
                        //伪删除部门及部门里得管理员
//                            DepartmentAdminModel::query()->where('department_id', $v['id'])->update($tempUpdate);
//                            $departmentModel->where('id', $v['id'])->update($tempUpdate);
                    } else {//删除资料
                        //开始删除与用户相关得数据
                        ConsultBlacklistModel::query()->where('uid', 'in', $ids)->delete();//心理咨询-黑名单表
                        ConsultOfflineModel::query()->where('uid', 'in', $ids)->delete();//线下咨询表
                        ConsultOfflineResultModel::query()->where('uid', 'in', $ids)->delete();//线下咨询量表测评结果表
                        ConsultOnlineModel::query()->where('uid', 'in', $ids)->delete();//线上咨询表
                        ConsultOnlineMessageModel::query()->where([['uid', 'in', $ids], ['who', '=', 1]])->delete();//线上咨询内容表
                        ConsultOnlineResultModel::query()->where('uid', 'in', $ids)->delete();//线上咨询量表测评结果表
                        CrisisLogModel::query()->where('uid', 'in', $ids)->delete();//危机干预-消息记录盒表
                        CrisisUserModel::query()->where('uid', 'in', $ids)->delete();//危机用户（危机上报）表
                        FollowUserModel::query()->where('uid', 'in', $ids)->delete();//关注用户（关注人群）表
                        InterfereUserModel::query()->where('uid', 'in', $ids)->delete();//干预人群表
                        InterpretationRecordModel::query()->where('uid', 'in', $ids)->delete();//申请解读记录表
                        LogModel::query()->where('uid', 'in', $ids)->delete();//系统日志表
                        LoginLogModel::query()->where('uid', 'in', $ids)->delete();//用户登录日志表
                        MessageModel::query()->where('uid', 'in', $ids)->delete();//用户接收的消息表
                        ProxyEvaluationResultModel::query()->where('uid', 'in', $ids)->delete();//代理测评结果（他人代测）表
                        SelfEvaluationResultModel::query()->where('uid', 'in', $ids)->delete();//自我测评结果表
                        TaskUserModel::query()->where('uid', 'in', $ids)->delete();//测评任务用户表
                        TaskUserResultModel::query()->where('uid', 'in', $ids)->delete();//任务用户答题结果表
                        TaskUserResultContinuityModel::query()->where('uid', 'in', $ids)->delete();//任务用户答题结果（因子预警连续测评）表
                        UserArchiveModel::query()->where('uid', 'in', $ids)->delete();//用户档案表
                        WarningReportRecordModel::query()->where('uid', 'in', $ids)->delete();//预警报告记录
                        $userMode->where('id', 'in', $ids)->delete();
                        //删除部门及部门里得管理员
//                            DepartmentAdminModel::query()->where('department_id', $v['id'])->delete();
//                            $departmentModel->where('id', $v['id'])->delete();
                    }
                }
            }
        }
    }

    /**
     * 区域任务
     */
    public function PlatformTask(): void
    {
        $PlatformTaskModel = new PlatformTaskModel();
        $data = $PlatformTaskModel->where('status', 'in', [1, 2])->select()->toArray();
        if (!empty($data)) {
            $TaskModel = new TaskModel();
            $PlatformTaskUnitModel = new PlatformTaskUnitModel();
            $update_status = [];
            $update_status2 = [];
            $update_task_unit = [];
            $update_task = [];
            foreach ($data as $value) {
                switch ($value['status']) {
                    case 1:
                        //未开始的任务
                        if ($value['start_time'] > time()) break;
                        $update_status[] = $value['id'];
                        break;
                    case 2:
                        //进行中的任务
                        if ($value['end_time'] <= time()) {
                            $warning_num = $value['warning_num'] ?? 0;
                            $unit_complete_num = $value['unit_complete_num'] ?? 0;
                            $update_status2[] = $value['id'];
                            //结束任务
                            $PlatformTaskUnitData = $PlatformTaskUnitModel->where([
                                ['task_id', '=', $value['id']],
                                ['is_submit', '=', 0],
                                ['unit_task_id', '>', 0]
                            ])->select()->toArray();
                            foreach ($PlatformTaskUnitData as $v) {
                                $unit_complete_num += 1;
                                $update_task_unit[] = $v['id'];
                                $update_task[] = $v['unit_task_id'];
                                $warning_num += $TaskModel->where('id', '=', $v['unit_task_id'])->value('warning_num') ?? 0;
                            }
                            $PlatformTaskModel->where('id', '=', $value['id'])->update([
                                'warning_num' => $warning_num,
                                'unit_complete_num' => $unit_complete_num,
                                'unit_complete_rate' => $unit_complete_num > 0 ? round($unit_complete_num / $value['unit_count'], 2) : 0,
                            ]);
                        } else {
                            $update_task[] = $value['id'];
                        }
                        break;
                }
            }
            //将未开始更新为进行中
            if (!empty($update_status)) {
                $PlatformTaskModel->where('id', 'in', $update_status)->update([
                    'status' => 2,
                ]);
            }
            //将进行中更新为已结束
            if (!empty($update_status2)) {
                $PlatformTaskModel->where('id', 'in', $update_status2)->update([
                    'status' => 3,
                ]);
            }
            //将单位任务提交
            if (!empty($update_task_unit)) {
                $PlatformTaskUnitModel->where('id', 'in', $update_task_unit)->update([
                    'is_submit' => 1,
                    'submit_time' => time(),
                    'submit_method' => 1,
                ]);
            }
            //将单位任务更新为已结束
            if (!empty($update_task)) {
                $TaskModel->where('id', 'in', $update_task)->update([
                    'status' => 3,
                ]);
            }
        }
    }

    /**
     * 团体活动
     */
    public function groupActivityTask(): void
    {
        $GroupActivityTaskModel = new GroupActivityTaskModel();
        $data = $GroupActivityTaskModel->where('status', 'in', [1, 2, 3, 4])->select()->toArray();
        $status2 = [];
        $status3 = [];
        $status4 = [];
        $status5 = [];
        $time = time();
        $ConfigModel = new ConfigModel();
        $configList = $ConfigModel->field('unit_id,value')->where('key','=','group_activity')->select()->toArray();
        $configData = [];
        foreach ($configList as $value) {
            $configData[$value['unit_id']] = json_decode($value['value']??0,true);
        }
        $GroupActivityTaskUserModel = new GroupActivityTaskUserModel();
        $MessageModel = new MessageModel();
        foreach ($data as $value) {
            switch ($value['status']) {
                case 1:
                    if ($time >= $value['enroll_start_time'] && $time <= $value['enroll_end_time']) {
                        $status2[] = $value['id'];
                    } elseif ($time > $value['enroll_end_time']) {
                        if ($value['is_sign'] == 1) {
                            $status3[] = $value['id'];
                        } else {
                            $status4[] = $value['id'];
                        }
                    }
                    break;
                case 2:
                    if ($time > $value['enroll_end_time']) {
                        if (!empty($configData[$value['unit_id']]['is_review_message'])){
                            $uid = $GroupActivityTaskUserModel->where([
                                ['task_id','=',$value['id']],
                                ['audit_status','=',2]
                            ])->distinct(true)->column('uid');
                            foreach ($configData[$value['unit_id']]['review_message'] as $channel) {
                                foreach ($uid as $v) {
                                    $MessageData[] = [
                                        'uid' => $v,
                                        'channel' => $channel,//接收渠道
                                        'type' => 23,
                                        'title' => '系统推送',
                                        'content' => $value['name'].'活动报名已结束！',
                                        'time' => time()
                                    ];
                                }
                            }
                            if (!empty($MessageData)){
                                $MessageModel->insertAll($MessageData,500);
                            }
                        }
                        if ($value['is_sign'] == 1) {
                            $status3[] = $value['id'];
                        } else {
                            $status4[] = $value['id'];
                        }
                    }
                    break;
                case 3:
                    if ($time >= $value['start_time'] && $time <= $value['end_time']) {
                        if (!empty($configData[$value['unit_id']]['is_sign_message'])){
                            $uid = $GroupActivityTaskUserModel->where([
                                ['task_id','=',$value['id']],
                                ['audit_status','=',2]
                            ])->distinct(true)->column('uid');
                            foreach ($configData[$value['unit_id']]['sign_message'] as $channel) {
                                foreach ($uid as $v) {
                                    $MessageData[] = [
                                        'uid' => $v,
                                        'channel' => $channel,//接收渠道
                                        'type' => 23,
                                        'title' => '系统推送',
                                        'content' => $value['name'].'活动报名已结束！',
                                        'time' => time()
                                    ];
                                }
                            }
                            if (!empty($MessageData)){
                                $MessageModel->insertAll($MessageData,500);
                            }
                        }
                        $status4[] = $value['id'];
                    } elseif ($time > $value['end_time']) {
                        $status5[] = $value['id'];
                    }
                    break;
                case 4:
                    if ($time > $value['end_time']) {
                        $status5[] = $value['id'];
                    }
                    break;
                default:
                    if ($time > $value['enroll_end_time']) {
                        $status5[] = $value['id'];
                    }
            }
        }
        if (!empty($status2)) {
            $GroupActivityTaskModel->where('id', 'in', $status2)->update([
                'status' => 2,
            ]);
        }
        if (!empty($status3)) {
            $GroupActivityTaskModel->where('id', 'in', $status3)->update([
                'status' => 3,
            ]);
        }
        if (!empty($status4)) {
            $GroupActivityTaskModel->where('id', 'in', $status4)->update([
                'status' => 4,
            ]);
        }
        if (!empty($status5)) {
            $GroupActivityTaskModel->where('id', 'in', $status5)->update([
                'status' => 5,
            ]);
        }
    }

    /**
     * 培训讲座
     */
    public function trainingTask(): void
    {
        $TrainingTaskModel = new TrainingTaskModel();
        $data = $TrainingTaskModel->field('id,status,start_time,end_time')->where('status', 'in', [1, 2])->select()->toArray();
        $status2 = [];
        $status3 = [];
        $time = time();
        foreach ($data as $value) {
            switch ($value['status']) {
                case 1:
                    if ($time >= $value['start_time'] && $time <= $value['end_time']) {
                        $status2[] = $value['id'];
                    } elseif ($time > $value['end_time']) {
                        $status3[] = $value['id'];
                    }
                    break;
                case 2:
                    if ($time > $value['end_time']) {
                        $status3[] = $value['id'];
                    }
                    break;
            }
        }
        if (!empty($status2)){
            $TrainingTaskModel->where('id', 'in', $status2)->update([
                'status' => 2,
            ]);
        }
        if (!empty($status3)){
            $TrainingTaskModel->where('id', 'in', $status3)->update([
                'status' => 3,
            ]);
        }
    }

    /**
     * 线下预约更新状态
     */
    public function consultOffline(): void
    {
        $ConsultOfflineModel = new ConsultOfflineModel();
        $data = $ConsultOfflineModel->field('id,time_id')
            ->where('situation','=',0)->with([
                'ConsultTime'
            ])->select()->toArray();
        $status = [];
        foreach ($data as $value) {
            if (time() > $value['reservation_start_time']){
                $status[] = $value['id'];
            }
        }
        if (!empty($status)){
            $ConsultOfflineModel->where('id', 'in', $status)->update([
                'situation' => 1,
            ]);
        }
    }

    /**
     * 问卷
     */
    public function questionnaireTask(): void
    {
        $QuestionnaireTaskModel = new QuestionnaireTaskModel();
        $data = $QuestionnaireTaskModel->field('id,status,start_time,end_time')->where([
            ['status', 'in', [1, 2]],
            ['is_time','=',1]
        ])->select()->toArray();
        $status2 = [];
        $status3 = [];
        $time = time();
        foreach ($data as $value) {
            switch ($value['status']) {
                case 1:
                    if ($time >= $value['start_time'] && $time <= $value['end_time']) {
                        $status2[] = $value['id'];
                    } elseif ($time > $value['end_time']) {
                        $status3[] = $value['id'];
                    }
                    break;
                case 2:
                    if ($time > $value['end_time']) {
                        $status3[] = $value['id'];
                    }
                    break;
            }
        }
        if (!empty($status2)){
            $QuestionnaireTaskModel->where('id', 'in', $status2)->update([
                'status' => 2,
            ]);
        }
        if (!empty($status3)){
            $QuestionnaireTaskModel->where('id', 'in', $status3)->update([
                'status' => 3,
            ]);
        }
    }

}